var fs=require('fs');
var http=require('http');
var formidable=require('formidable');
var path=require('path');
var server=http.createServer(function (req, res) {
    if('/'==req.url){
        switch(req.method){
            case 'GET':
                show(req,res);
                break;

            case 'POST':
                upload(req,res);
                break;

            default:
                show(req,res);
        }
    }else{
        res.statusCode=404;
        res.end('Not Found.');
    }
});

server.listen(3000,function () {
  console.log('----------------------------port 3000',new Date());
});

var html=fs.readFileSync('./upload.html');
function show(req, res) {
    res.setHeader('Content-Type','text/html');
    res.setHeader('Content-Length',Buffer.byteLength(html));
    res.end(html);
}

function upload(req, res) {
    if(!isFormData(req)){
        res.statusCode=400;
        res.end('Bad req!');
        return;
    }
    var form=new formidable.IncomingForm();
    form.uploadDir='./tmp';
    form.parse(req,function (err,fields, files) {
        if(err)return console.log(err);
        console.log('Parse:',fields,files);
        for(var name in files){
            var file=files[name];
            var newPath=(function(){
                var extname=path.extname(file.name);
                return path.basename(file.path)+'_'+Date.now()+extname;
            })(file);
            fs.rename(file.path,'./upload/'+newPath,function (err) {
                if(err)return console.log('rename err:',err);
            });
        }
    });//此方法相当于以下三个函数的封装


    form.on('field',function (field, value) {
        console.log('Field:',field,value);
    });

    form.on('file',function (name, file) {
        console.log('File:',name,file);
    });

    form.on('end',function () {
        console.log('End:',arguments);
        res.end('Upload complete!');
    });

    //进度
    form.on('progress',function (bytesReceived, bytesExpected) {
       console.log(bytesReceived, bytesExpected);
    });

}

function isFormData(req) {
    var type=req.headers['content-type'] || '';
    return !!~type.indexOf('multipart/form-data');
}
